/**
 * 所有接口请求
 */
import {
  baseUrl,
} from '/common/config';

const defHeaders = {
  'Content-Type': 'application/json;charset=UTF-8',
}

/**
 * userAuth 用户授权登录认证
 */
export const userAuth = (authCode) => {
  return new Promise((resolve, reject) => {
    my.httpRequest({
      url: `${baseUrl}/api/account`,
      method: 'POST',
      data: {
        authCode,
      },
      success: (res) => {
        resolve(res);
      },
      fail: (res) => {
        reject(res);
      }
    });
  });
}

/**
 * getAccountInfo 获取账户信息
 */
export const getAccountInfo = () => {
  return new Promise((resolve, reject) => {
    const { data: userId } = my.getStorageSync({
      key: 'userId',
    });
    if ( userId ) {
      my.httpRequest({
        url: `${baseUrl}/api/account`,
        headers: {
          ...defHeaders,
        },
        data: {
          userId,
        },
        success: (res) => {
          resolve(res);
        },
        fail: (res) => {
          reject(res);
        }
      });
    } else {
      reject();
    }
  });
}

/**
 * getOrders 获取订单流水
 */
export const getOrders = () => {
  return new Promise((resolve, reject) => {
    const { data: userId } = my.getStorageSync({
      key: 'userId',
    });
    if ( userId ) {
      my.httpRequest({
        url: `${baseUrl}/api/orders`,
        data: {
          userId,
        },
        success: (res) => {
          resolve(res);
        },
        fail: (res) => {
          reject(res);
        }
      });
    } else {
      reject();
    }
  });
}

/**
 * transfer 转账
 */
export const transfer = (sellerId, payAmount) => {
  return new Promise((resolve, reject) => {
    const { data: userId } = my.getStorageSync({
      key: 'userId',
    });
    if ( userId ) {
      my.httpRequest({
        url: `${baseUrl}/api/orders`,
        headers: {
          ...defHeaders,
        },
        method: 'POST',
        data: JSON.stringify({
          buyerId: userId,
          sellerId: sellerId,
          payAmount: Number(payAmount)
        }),
        success: (res) => {
          resolve(res);
        },
        fail: (res) => {
          reject(res);
        }
      });
    } else {
      reject();
    }
  });
}

/**
 * getAllAccountInfo 获取所有账户信息
 */
export const getAllAccountInfo = () => {
  return new Promise((resolve, reject) => {
    my.httpRequest({
      url: `${baseUrl}/api/accounts/all`,
      headers: {
        ...defHeaders,
      },
      success: (res) => {
        resolve(res);
      },
      fail: (res) => {
        reject(res);
      }
    });
  });
}